package com.salon.modules.sys.service.impl;

import com.salon.common.http.response.ObjectResult;
import com.salon.common.utils.RedisKeys;
import com.salon.common.utils.RedisUtils;
import com.salon.modules.app.utils.JwtUtils;
import com.salon.modules.sys.service.ISysUserTokenService;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

@Service("sysUserTokenService")
public class SysUserTokenServiceImpl implements ISysUserTokenService {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public ObjectResult createToken(long userId) {
        String oldToken = (String) redisUtils.get(RedisKeys.getSysTokenKey(String.valueOf(userId)));
        if (ObjectUtils.isEmpty(oldToken)) {
            redisUtils.del(RedisKeys.getSysTokenKey(String.valueOf(userId)));
        }
        String userIdStr = String.valueOf(userId);
        oldToken = jwtUtils.getAdminToken(userIdStr);
        redisUtils.set(RedisKeys.getSysTokenKey(userIdStr), oldToken, jwtUtils.getAdminExpire());
        Map<String, Object> result = new HashMap<>();
        result.put("token", oldToken);
        result.put("expire", jwtUtils.getAdminExpire());
        return ObjectResult.success(result);
    }

    @Override
    public String getSysUserIdByJwtToken(String accessToken) {
        return jwtUtils.getSysUserIdByJwtToken(accessToken);
    }

    @Override
    public boolean checkToken(String accessToken) {
        return jwtUtils.checkToken(accessToken);
    }

    @Override
    public Object getSysTokenBySysUserId(String sysUserId) {
        return redisUtils.get(RedisKeys.getSysTokenKey(sysUserId));
    }

    @Override
    public void logout(long userId) {
        redisUtils.del(RedisKeys.getSysTokenKey(String.valueOf(userId)));
    }

    @Override
    public void removeToken(Long userId) {
        redisUtils.del(RedisKeys.getSysTokenKey(String.valueOf(userId)));
    }

}
